package com.ant.sha1.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * Created by baichuan on 2016/12/9.
 */
public class Base64Utils {
    private static final String CHARSET_NAME="UTF-8";

    public static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D',
            'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
            'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
            'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
            'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3',
            '4', '5', '6', '7', '8', '9', '+', '/'};


    public static String encode64(String data) {
        if (isEmpty(data))
            return null;
        try {
            byte[] md=data.getBytes(CHARSET_NAME);
            return new BASE64Encoder().encode(md);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decode64(String data) {
        if (isEmpty(data))
            return null;
        try {
            return new String(new BASE64Decoder().decodeBuffer(data), CHARSET_NAME);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    public static boolean isEmpty(String data) {
        return data == null || "".equals(data);
    }
}
